import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class 三数之和 {
    public static void main(String[] args) {
        List<List<Integer>> lists = threeSum(new int[]{-1, 0, 1, 2, -1, -4});
        System.out.println(lists);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        //排序
        Arrays.sort(nums);

        //遍历每一个数
        int length = nums.length;
        List<List<Integer>> resultList = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            //收取结果后，去重
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            //最小的数都大于0了，后面的就不用看了
            if (nums[i] > 0)
                break;
            //找其余两个数
            int left = i + 1;
            int right = length - 1;
            while (left < right) {
                //看是否等于0
                if (nums[i] + nums[left] + nums[right] > 0)
                    right--;
                else if (nums[i] + nums[left] + nums[right] < 0)
                    left++;
                else {
                    resultList.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    //对中间数去重
                    while (left < right && nums[left] == nums[left + 1])
                        left++;
                    while (left < right && nums[right] == nums[right - 1])
                        right--;
                    left++;
                    right--;
                }
            }

        }
        return resultList;
    }
}